package cn.edu.zxj.rabbitmqmyself.util;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-10-02
 * @time: 00:38:40
 */
public class FileUtil {
    /*
     *  从输入流中读取数据, 并写入到指定文件中
     */
    public static void writeFromStream(String filePath, InputStream inputStream) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        }
    }

    /*
     *  从文件中读取数据, 返回
     */
    public static String readFromFile(String filePath) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = new FileInputStream(filePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuilder.append(new String(buffer, 0, len));
            }
        }
        return stringBuilder.toString();
    }

    /*
     * 向文件中写数据
     */
    public static void writeToFile(String filePath, String content) throws IOException {
        try (OutputStream outputStream = new FileOutputStream(filePath)) {
            outputStream.write(content.getBytes());
        }
    }

}
